<template>
	<div>
		<el-dialog v-model="dialog" title="素材" width="70%" append-to-body>
			<el-upload
				append-to-body
				:action="action"
				:headers="headers"
				:multiple="true"
				:limit="5"
				:show-file-list="false"
				:before-upload="beforeUpload"
				:on-success="handleSuccess"
				:on-error="handleError"
			>
				<el-button type="primary">
					<el-icon> <ele-Upload /> </el-icon>上传图片</el-button
				>
			</el-upload>
			<div class="material-main">
				<div class="category" v-loading="groupLoading">
					<el-tree
						ref="treeRef"
						:data="treeList"
						:props="defaultProps"
						class="category-tree"
						@current-change="currentChange"
						:highlight-current="true"
					/>
				</div>
				<div class="media-list" v-loading="loading">
					<h1 class="title">{{ groupTitle }}</h1>
					<div class="image-list">
						<div class="image-item" v-for="(item, index) in materialList" :key="index">
							<el-card>
								<div class="image-box" @click="chooseImageHandler(item)" :style="{ backgroundImage: 'url(' + item.url + ')' }">
									<div :class="['attachment-selected', { active: chooseImages.find((x) => x.id === item.id) }]">
										<i class="iconfont icon-duihao" style="top: -8px; right: -3px" />
										<span class="after" />
									</div>
								</div>
								<div class="image-title">{{ item.name }}</div>
							</el-card>
						</div>
					</div>
					<!-- 分页 -->
					<pagination
						v-model:total="page.total"
						v-model:currentPage="page.currentPage"
						v-model:pageSize="page.pageSize"
						@changePage="initPage"
						:page-sizes="[10, 50]"
					></pagination>
				</div>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialog = false">关 闭</el-button>
					<el-button type="primary" @click="submit">确 认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, computed } from 'vue';
import { getPage, addObj } from '/@/api/mall/material';
import { getList } from '/@/api/mall/materialgroup';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
import type { UploadProps } from 'element-plus';
interface DataState {
	page: {
		total: number;
		currentPage: number;
		pageSize: number;
	};
	queryParams: {
		groupId: string;
	};
	treeList: Array<any>;
	materialList: Array<any>;
	chooseImages: Array<any>;
}
export default defineComponent({
	props: {
		canChooseImagesNum: {
			type: Number,
			default: 1,
		},
	},
	setup(props, { emit }) {
		const data = reactive<DataState>({
			page: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
			},
			queryParams: {
				groupId: '',
			},
			treeList: [],
			materialList: [],
			chooseImages: [],
		});
		const groupLoading = ref(false);
		const groupTitle = ref('');
		const groupName = ref('');
		const groupPopover = ref(false);

		const { page, treeList, materialList, queryParams, chooseImages } = toRefs(data);
		const headers = {
			satoken: Session.get('token'),
		};
		const action = '/upms/file/upload?fileType=image';
		const defaultProps = {
			children: 'children',
			label: 'name',
			id: 'id',
		};
		const loading = ref(false);
		const dialog = ref(false);
		const picList = ref([]);
		const chooseImagesNum = ref(props.canChooseImagesNum); // 选择图片数量

		/**
		 * 素材分页列表
		 */
		const initPage = () => {
			loading.value = true;
			getPage({
				current: page.value.currentPage,
				size: page.value.pageSize,
				groupId: queryParams.value.groupId ? queryParams.value.groupId : '-1',
				descs: 'create_time',
			})
				.then((response) => {
					loading.value = false;
					materialList.value = response.data.data.records;
					page.value.total = response.data.data.total;
				})
				.catch(() => {
					loading.value = false;
				});
		};
		/**
		 * 上传素材前事件
		 */
		const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
			if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
				ElMessage.error('Avatar picture must be JPG or png format!');
				return false;
			} else if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage.error('Avatar picture size can not exceed 2MB!');
				return false;
			}
			return true;
		};
		/**
		 * 上传成功事件
		 */
		const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
			let params = {
				url: response.data,
				type: 1,
				name: uploadFile.name,
				groupId: queryParams.value.groupId ? queryParams.value.groupId : '-1',
			};
			addObj(params)
				.then((response: any) => {
					if (response.data.code == 0) {
						ElMessage.success('上传成功');
						initPage();
					} else {
						ElMessage.error(response.data.msg);
					}
				})
				.catch(() => {});
		};
		/**
		 * 上传失败事件
		 */
		const handleError: UploadProps['onError'] = (error) => {
			ElMessage.error(error + '');
		};

		/**
		 * 素材分组列表查询
		 */
		const getGroup = () => {
			groupLoading.value = true;
			getList({})
				.then((response) => {
					treeList.value = response.data.data;
					treeList.value.unshift({ id: '-1', name: '未分组' });
					groupTitle.value = groupTitle.value ? groupTitle.value : '未分组';
					groupLoading.value = false;
				})
				.catch(() => {
					groupLoading.value = false;
				});
		};
		/**
		 * 切换分组
		 */
		const currentChange = (data: any) => {
			queryParams.value.groupId = data.id;
			groupTitle.value = data.name;
			initPage();
		};
		/**
		 * 选择图片
		 */
		const chooseImageHandler = (item: any) => {
			if (props.canChooseImagesNum === 1) {
				chooseImages.value = [];
			}
			/** 判断是否已经存在*/
			const $index = chooseImages.value.findIndex((x) => x.id === item.id);
			if (props.canChooseImagesNum > 1 && $index >= 0) {
				chooseImages.value.splice($index, 1);
			} else {
				if (chooseImages.value.length >= props.canChooseImagesNum) {
					ElMessage.error(`只能选择${props.canChooseImagesNum}张图片`);
					return;
				}
				chooseImages.value.push(item);
			}
		};
		/**
		 * 确认按钮
		 */
		const submit = () => {
			if (chooseImages.value.length <= 0) {
				ElMessage.error('请选择素材');
				return;
			}
			let imageList: Array<any> = [];
			chooseImages.value.map((img) => {
				imageList.push(img.url);
			});
			emit('changeImg', imageList);
			restChoose();
		};
		const restChoose = () => {
			dialog.value = false;
			chooseImages.value = [];
		};
		getGroup();
		initPage();
		return {
			dialog,
			picList,
			chooseImagesNum,
			chooseImages,
			headers,
			action,
			defaultProps,
			loading,
			groupLoading,
			groupTitle,
			groupName,
			groupPopover,
			page,
			treeList,
			materialList,
			beforeUpload,
			handleSuccess,
			handleError,
			getGroup,
			currentChange,
			chooseImageHandler,
			submit,
			initPage,
		};
	},
});
</script>
<style lang="scss">
.material-pic-list {
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
.material-pic-item {
	position: relative;
	border: 1px solid #efefef;
	width: 60px;
	height: 60px;
	line-height: 60px;
	text-align: center;
	margin-right: 10px;
	cursor: pointer;
}
.material-icon {
	font-size: 30px;
	position: absolute;
	z-index: 1;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	right: -10px;
	top: -28px;
	color: #999999;
}
.material-main {
	display: flex;
	min-height: 550px;
	height: calc(max(100vh - 550px, 300px));
	margin-top: 15px;
	.category {
		display: flex;
		flex-direction: column;
		flex: none;
		width: 240px;
		box-sizing: border-box;
		border: 1px solid #dcdee0;
		margin-right: -1px;
		overflow: hidden;
		.category-tree {
			padding: 20px;
		}
		.footer {
			position: absolute;
			bottom: 2px;
			width: 240px;
			box-sizing: border-box;
			text-align: center;
			padding: 12px 0;
			height: 56px;
			box-shadow: 0 -1px 4px 0 rgb(0 0 0 / 10%);
		}
	}
	.media-list {
		flex: auto;
		box-sizing: border-box;
		border: 1px solid #dcdee0;
		padding: 12px;
		overflow-y: auto;
		.title {
			font-size: 16px;
			line-height: 24px;
			font-weight: 700;
			color: #323233;
		}
	}
}
.image-list {
	display: flex;
	flex-wrap: wrap;
	overflow: hidden;
	.image-item {
		position: relative;
		width: 160px;
		margin: 6px;
		.image-box {
			box-sizing: content-box;
			position: relative;
			height: 0;
			width: 100%;
			padding-bottom: 100%;
			cursor: pointer;
			background-color: #f7f8fa;
			background-position: 50%;
			background-size: cover;
			background-repeat: no-repeat;
			overflow: hidden;
		}
		.image-title {
			margin: 8px 0 4px;
			font-size: 14px;
			line-height: 20px;
			height: 20px;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
		}
		.image-bar {
			font-size: 0;
			height: 20px;
			button {
				margin-left: 0;
				padding: 0 3px;
			}
		}
	}
}
.popover-input {
	display: flex;
	justify-content: space-between;
}
.attachment-selected {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	border: 2px solid #07d;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	cursor: pointer;
	opacity: 0;

	&:hover,
	&.active {
		opacity: 1;
	}

	i {
		position: absolute;
		right: 1px;
		top: 1px;
		z-index: 7;
		font-size: 12px;
		color: #fff;
	}

	span.after {
		position: absolute;
		display: block;
		content: ' ';
		right: 0;
		top: 0;
		border: 14px solid #07d;
		border-left-color: transparent;
		border-bottom-color: transparent;
		z-index: 1;
	}
}
</style>
